package com.gxa.autoparts.core.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Map;

public class JsonUtil {

    private static ObjectMapper objectMapper=null;

    static {
        objectMapper=new ObjectMapper();
    }

    /**
     * 将字符串转换成对象
     * @param jsonString
     * @param clazz
     * @param <T>
     * @return
     * @throws JsonProcessingException
     */
    public static <T> T readToObject(String jsonString,Class<T> clazz) {

        T t = null;
        try {
            t = objectMapper.readValue(jsonString, clazz);
        } catch (JsonProcessingException e) {
            //工具类的异常也应该记录日志当中
            e.printStackTrace();
        }

        return t;

    }


    /**
     * 将对象转换成字符串
     * @param object
     * @return
     */
    public static String ObjectToString(Object object) {
        String jsonString=null;

        try {
            jsonString = objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {

            //工具类的异常也应该记录日志当中
            e.printStackTrace();
        }

        return jsonString;

    }


    public static <T>T mapToObject(Map map, Class<T> tClass){
        T t = null;
        String s = ObjectToString(map);
        t = readToObject(s, tClass);
        return t;
    }


}
